package com.dayatang.product.webapp.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Date;

import javax.activation.FileDataSource;
import javax.mail.internet.MimeUtility;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import com.dayatang.domain.InstanceFactory;
import com.dayatang.product.application.ProductApplication;
import com.dayatang.product.domain.Attachment;
import com.dayatang.product.domain.EmailInfo;
import com.dayatang.product.domain.HtmlMail;
import com.dayatang.product.domain.MailReceiver;
import com.dayatang.product.domain.RegisterInfo;

public class MailUtil {

	private static ProductApplication productApplication;
	
	public static ProductApplication getProductApplication() {
		if (productApplication == null) {
			productApplication = InstanceFactory.getInstance(ProductApplication.class);
		}
		return productApplication;
	}

	public void setProductApplication(ProductApplication productApplication) {
		MailUtil.productApplication = productApplication;
	}

	public static void sendMail(HtmlMail htmlMail, MailReceiver mailReceiver) {
		sendHtmlMail(htmlMail,mailReceiver);
	}
	
	public static void sendMail(String registerCode, RegisterInfo registerInfo, HtmlMail htmlMail) {
		sendHtmlMail(registerCode,registerInfo,htmlMail);
	}
	
	/**
	 * @param htmlMail
	 * @param mailReceiver
	 */
	private static void sendHtmlMail(HtmlMail htmlMail, MailReceiver mailReceiver) {
		HtmlEmail email = null;
		try {
			email = initHtmlEmail(htmlMail.getEmailInfo());
			email.addTo(mailReceiver.getCustomer().getEmail());
			email.setCharset("UTF-8");
			email.setSubject(htmlMail.getSubject());
			email.setHtmlMsg(htmlMail.getHtmlMsg());
			if (htmlMail.getAttachments().size() > 0) {
				addAttachment(email,htmlMail);
			}
			email.send();
			mailReceiver.setSendDate(new Date());
			mailReceiver.setSuccess(true);
		} catch (EmailException e) {
			mailReceiver.setSuccess(false);
			mailReceiver.setError(e.toString());
		} catch (MalformedURLException e) {
			mailReceiver.setSuccess(false);
			mailReceiver.setError(e.toString());
		} catch (UnsupportedEncodingException e) {
			mailReceiver.setSuccess(false);
			mailReceiver.setError(e.toString());
		} finally {
			getProductApplication().saveEntity(mailReceiver);
		}
	}
	
	private static void sendHtmlMail(String registerCode, RegisterInfo registerInfo, HtmlMail htmlMail) {
		HtmlEmail email = null;
		try {
			if (htmlMail != null) {
				email = initHtmlEmail(htmlMail.getEmailInfo());
				email.addTo(registerInfo.getEmail());
				email.setCharset("UTF-8");
				email.setSubject(htmlMail.getSubject());
				email.setHtmlMsg(processRegisterCode(htmlMail.getHtmlMsg(),registerCode,registerInfo.getCompanyName()));
				if (htmlMail.getAttachments().size() > 0) {
					addAttachment(email,htmlMail);
				}
				email.send();
				registerInfo.setSend(true);
			} else {
				registerInfo.setSend(false);
				registerInfo.setError("找不到发送邮件");
			}
		} catch (EmailException e) {
			registerInfo.setSend(false);
			registerInfo.setError(e.toString());
		} catch (MalformedURLException e) {
			registerInfo.setSend(false);
			registerInfo.setError(e.toString());
		} catch (UnsupportedEncodingException e) {
			registerInfo.setSend(false);
			registerInfo.setError(e.toString());
		} finally {
			getProductApplication().saveEntity(registerInfo);
		}
	}

	
	private static HtmlEmail initHtmlEmail(EmailInfo emailInfo) throws EmailException {
		HtmlEmail email = new HtmlEmail();
		email.setHostName(emailInfo.getSmtpName());
		email.setSmtpPort(emailInfo.getSmtpPort());
		email.setAuthenticator(new DefaultAuthenticator(emailInfo.getUsername(),emailInfo.getPassword()));
		email.setTLS(false);
		if (emailInfo.getName() != null) {
			email.setFrom(emailInfo.getUsername(),emailInfo.getName());
		} else {
			email.setFrom(emailInfo.getUsername());
		}
		return email;
	}
	
	private static void addAttachment(HtmlEmail email, HtmlMail htmlMail) throws EmailException, MalformedURLException, UnsupportedEncodingException {
		for (Attachment attachment : htmlMail.getAttachments()) {
			File file = new File(attachment.getPath());
			if (file.exists()) {
				email.embed(new FileDataSource(file),MimeUtility.encodeText(file.getName()));
			}
		}
	}
	
	private static String processRegisterCode(String htmlMsg, String registerCode, String companyName) {
		return htmlMsg.replaceAll("XXXXX", companyName).replaceAll("1234567", registerCode);
	}
	
}
